<template>
  <div ref="chartRef" :style="{ height: height, width: width }"></div>
</template>

<script setup>
import { ref, onMounted, watch, defineProps } from 'vue';
import * as echarts from 'echarts';
import { darkTheme, lightTheme } from './chartThemes';

const props = defineProps({
  chartData: {
    type: Object,
    default: () => ({ labels: [], values: [] })
  },
  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '100%'
  },
   theme: {
    type: String,
    default: 'light'
  }
});

const chartRef = ref(null);
let myChart = null;

const themes = {
  dark: darkTheme,
  light: lightTheme
};

const initChart = () => {
  if (chartRef.value) {
    myChart = echarts.init(chartRef.value, props.theme === 'dark' ? themes.dark : null);
    setOptions(props.chartData);
  }
};

const setOptions = (data) => {
  if (!myChart || !data.labels || !data.values) return;
  myChart.setOption({
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '10%',
      containLabel: true
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: data.labels,
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      data: data.values,
      type: 'line',
      smooth: true,
      symbol: 'none',
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
            offset: 0,
            color: 'rgba(80,141,255,0.3)'
        }, {
            offset: 1,
            color: 'rgba(80,141,255,0)'
        }])
      },
    }]
  });
};

watch(() => props.chartData, (newData) => {
  if(myChart) {
    setOptions(newData);
  }
});

watch(() => props.theme, (newTheme) => {
    if (myChart) {
        myChart.dispose();
        initChart();
    }
});

onMounted(() => {
  initChart();
});
</script> 